package com.znyj.servlet.service;

import com.znyj.servlet.dao.UserDao;
import com.znyj.servlet.entity.UserEntity;
import com.znyj.servlet.model.UserQueryModel;
import com.znyj.servlet.sqlHelper.SqlRequest;
import com.znyj.servlet.vo.Page;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by gaoliwei02 on 17/7/6.
 */
@Service
public class UserService {
    private static final Logger logger = Logger.getLogger(UserService.class);

    @Autowired
    private UserDao userDao;

    public int insertUser(UserEntity userEntity) {
        return userDao.insert(userEntity);
    }

    public int updateUser(UserEntity userEntity) {
        return userDao.update(userEntity);
    }

    public UserEntity findByUsername(String userName) {
        return userDao.findByUsername(userName);
    }

    public int updateUserInfo(Timestamp lastSignTime, int signStatus, String ipAddress, String userName) {
        return userDao.updateUserInfo(lastSignTime, signStatus, ipAddress, userName);
    }

    public Page<UserEntity> createUserPage(UserQueryModel userQueryModel) {
        int skip = userQueryModel.getOffset();
        SqlRequest sqlRequest = new SqlRequest("cdb_user", "*");

        if (userQueryModel.getUsername() == null || userQueryModel.getUsername().equals("") || userQueryModel.getUsername().equals("all")) {

        } else {
            sqlRequest.EQ("username", userQueryModel.getUsername());
        }

        if (userQueryModel.getRole_permission() == -1) {

        } else {
            sqlRequest.EQ("role_permission", userQueryModel.getRole_permission());
        }

        int count = userDao.count(sqlRequest);
        sqlRequest.Limit(skip, userQueryModel.getPageSize());
        if (userQueryModel.getPageSize() == -1) {
            return null;
        }

        List<UserEntity> cdbUserEntities = userDao.query(sqlRequest);


        Page<UserEntity> page = Page.createPage(userQueryModel.getPageNumber(), userQueryModel.getPageSize(), cdbUserEntities, count);
        return page;
    }
}
